# coding=utf-8

import json

from django.core import serializers
from django.core.urlresolvers import reverse
from django.db import connection
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import get_object_or_404, render
from django.template import loader

from polls.json_mapping import JsonMapping
from .models import Choice, Question


def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    template = loader.get_template('polls/index.html')
    context = {
        'latest_question_list': latest_question_list,
    }
    return HttpResponse(template.render(context, request))


def test(request):
    response_data = {}
    response_data['result'] = 'failed'
    response_data['message'] = 'You messed up'
    return HttpResponse(json.dumps(response_data), content_type="application/json")


def test_xml(request):
    latest_question_list = Question.objects.all()
    data = serializers.serialize("xml", latest_question_list)
    return HttpResponse(data, content_type="application/json")


def test_json1(request):
    latest_question_list = Question.objects.all()
    data = serializers.serialize("json", latest_question_list)
    return HttpResponse(data, content_type="application/json")


def sql_query(request):
    cursor = connection.cursor()
    cursor.execute('select * from demo_task')
    raw = cursor.fetchone()
    dic = dict()
    dic['id'] = raw[0]
    dic['title'] = raw[6]
    dic['description'] = raw[7]
    jm = JsonMapping()
    dt = jm.dump_to_json(dic)
    return HttpResponse(dt, content_type="application/json")


def sql_query_test_city(request, city_id):
    print('city is %s', city_id)
    cursor = connection.cursor()
    cursor.execute('select * from demo_city where id = %s', city_id)
    raws = cursor.fetchall()
    lst = []
    for x in raws:
        dic = dict()
        dic['id'] = x[0]
        dic['name'] = x[6]
        dic['state'] = x[7]
        dic['country'] = x[8]
        lst.append(dic)

    jm = JsonMapping()
    dt = jm.dump_to_json(lst)
    return HttpResponse(dt, content_type="application/json")


def sql_query2(request):
    cursor = connection.cursor()
    cursor.execute('select * from demo_task')
    raws = cursor.fetchall()
    lst = []
    for x in raws:
        dic = dict()
        dic['id'] = x[0]
        dic['title'] = x[6]
        dic['description'] = x[7]
        lst.append(dic)

    jm = JsonMapping()
    dt = jm.dump_to_json(lst)
    return HttpResponse(dt, content_type="application/json")


def sql_update_trx(request, task_id):
    print('task_id is ', task_id)
    sql1 = "update demo_task a set a.title = 'updated' where id = \'%d\'" % int(task_id)
    print('sql1 is ', sql1)
    cursor = connection.cursor()
    rst = cursor.execute(sql1)
    response = rst
    return HttpResponse(response)


def detail(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/detail.html', {'question': question})


def results(request, question_id):
    response = "You're looking at the results of question %s."
    return HttpResponse(response % question_id)


def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(request, 'polls/detail.html', {
            'question': question,
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
